#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include"Log.hpp"
#include"Common.hpp"
using namespace LogModule;
int main(int args,char* argv[])
{
    if(args!=3)
    {
        LOG(Loglevel::FATAL)<<"Usage:./client_tcp server_ip server_port";
        Die(USAGE_ERROR);
    }
    std::string server_ip=argv[1];
    uint16_t server_port=std::stoi(argv[2]);
    //创建TCP套接字
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        LOG(Loglevel::FATAL)<<"socket filed";
        Die(SOCKET_ERROR);
    }
    LOG(Loglevel::INFO)<<"socket success,sockfd:"<<sockfd;
    //填充网络信息
    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(server_port);
    server_addr.sin_addr.s_addr=inet_addr(server_ip.c_str());
    //客户端不需要显式进行bind
    //TCP面向连接,需要先与服务端建立连接
    int n=connect(sockfd,CONV(&server_addr),sizeof(server_addr));
    if(n<0)
    {
        LOG(Loglevel::ERROR)<<"connect filed";
        Die(CONNECT_ERROR);
    }
    LOG(Loglevel::INFO)<<"connect success,sockfd:"<<sockfd;
    std::string message;
    while(true)
    {
        char inbuffer[1024];
        std::cout<<"input message#";
        getline(std::cin,message);
        int n=send(sockfd,message.c_str(),sizeof(message),0);
        if(n>0)
        {
            int m=recv(sockfd,inbuffer,sizeof(inbuffer),0);
            if(m>0)
            {
                inbuffer[m]=0;
                std::cout<<inbuffer<<std::endl;
            }
        }
    }
    close(sockfd);
    return 0;
}